//
//  ParameterEncrypt.swift
//  ZYChat
//
//  Created by admin on 2019/11/14.
//  Copyright © 2019 admin. All rights reserved.
//

import Foundation
import CryptoSwift




//参数加密
public struct ParameterEncrypt {
    
    // 获取时间戳
    private static func getCurrentTimestamp() -> String{
        
        let now = Date()
        let formatter = DateFormatter()
        formatter.dateFormat = "YYYY-MM-dd HH:mm:ss SSS"
        
        let timezone = TimeZone(identifier:"Asia/Shanghai")!
        formatter.timeZone = timezone
        let t = Int(now.timeIntervalSince1970*1000)
        return String.init(format: "%ld", t)
    }
    
    //参数加密
    public static func encrypt(paramet: Dictionary<String, Any>?, url: String) -> Dictionary<String, Any> {
        
        let urlArr = url.components(separatedBy: "/")
        let lastURl = urlArr.last!
        var parametVar: Dictionary<String, Any>;
        if paramet != nil {
           parametVar = paramet!
        }else{
            parametVar = Dictionary.init()
        }
         
        parametVar.updateValue(getCurrentTimestamp(), forKey: "timestamp")
        let parametKeys = parametVar.keys
        let sorteKeys = parametKeys.sorted {$1 > $0}
        
        
        var urlStr:String = lastURl
        for key in sorteKeys {
            urlStr.append(contentsOf: key)
            urlStr.append(contentsOf: parametVar[key] as! String)
        }
        
        urlStr.append("zilot")
        let urlMd5 = urlStr.md5
        
        parametVar.updateValue(urlMd5, forKey: "sign")
        
        do {
            let aes = try AES.init(key: "szzhongyuanzilot", iv: "zilotszzhongyuan")
            let cSet = CharacterSet.init(charactersIn:"%+/?#&= ").inverted
            
            for key in sorteKeys {
                let value = parametVar[key] as! String
                do {
                    var encryptd = try value.encryptToBase64(cipher: aes)
                    akLog(encryptd)
                    encryptd = encryptd.addingPercentEncoding(withAllowedCharacters: cSet)!
                    parametVar.updateValue(encryptd, forKey: key)
                } catch {
                    akLog(error)
                }
            }
            var vl:String = parametVar["sign"] as! String
            vl = try! vl.encryptToBase64(cipher: aes)
            parametVar.updateValue(vl, forKey: "sign")
            
        } catch {
            print(error)
        }
        
        return parametVar
    }
    

}
